package ar.edu.itba.it.cg.grupo01.impl.texture;

import java.awt.Color;
import java.awt.image.BufferedImage;

import ar.edu.itba.it.cg.grupo01.api.texture.TextureFilter;
import ar.edu.itba.it.cg.grupo01.impl.color.Colors;

public class BilinearFilter implements TextureFilter {

	//TODO:optimizar
	@Override
	public Color getTextureColor(float u, float v, BufferedImage img) {
		
		Color point00=new Color(0);
		Color point01=new Color(0);
		Color point10=new Color(0);
		Color point11=new Color(0);
		
		
//		int p=0;
		int floorU=(int)Math.floor(u*img.getWidth());
		int floorV=(int)Math.floor(v*img.getHeight());
		int topU=(int)Math.ceil(u*img.getWidth());
		int topV=(int)Math.ceil(v*img.getHeight());
		
		floorU=Math.max(floorU, 0);
		floorV=Math.max(floorV, 0);
		topU=Math.max(topU, 0);
		topV=Math.max(topV, 0);
		if(topU>=img.getWidth())
			topU=img.getWidth()-1;
		if(topV>=img.getHeight())
			topV=img.getHeight()-1;
		
		
try{
		 point00=new Color(img.getRGB(floorU,floorV));
		 point01=new Color(img.getRGB(floorU,topV));
		 point10=new Color(img.getRGB(topU,floorV));
		 point11=new Color(img.getRGB(topU,topV));
		
}catch(java.lang.ArrayIndexOutOfBoundsException e){
		System.out.println("error reading texture " + u*img.getWidth() +"," + v*img.getHeight() );
}

		float du=img.getWidth()*u - floorU;
		float dv=img.getHeight()*v - floorV;

		Color p1=Colors.scale(point10, 1- du);
		p1=Colors.addTo(p1, Colors.scale(point11, du));
		Color p2=Colors.scale(point00, 1- du);
		p2=Colors.addTo(p2, Colors.scale(point01, du));
		
		Color p=Colors.addTo(Colors.scale(p1,1-dv), Colors.scale(p2, dv));		
	
		return p;
	}

}
